import { useEffect, useState, useRef } from "react";
import { Layout, Menu, message, Button, Upload, Space, Typography } from "antd";
import {
  SettingOutlined,
  CloudDownloadOutlined,
  PlayCircleOutlined,
  StopOutlined,
  FileTextOutlined,
  CodeOutlined,
  UploadOutlined,
  DownloadOutlined
} from "@ant-design/icons";
import StartStop from "./components/StartStop";
import ProxyConfig from "./components/ProxyConfig";
import VersionDownload from "./components/VersionDownload";
import ConfigPanel from "./components/ConfigPanel";
import Logs from "./components/Logs";

const { Header, Sider, Content } = Layout;
const { Title, Text } = Typography;
const MENU_STORAGE_KEY = "myapp_selectedMenuKey";

const App = () => {
  const [collapsed, setCollapsed] = useState(false);
  // const [selectedMenu, setSelectedMenu] = useState("startStop");
  const [proxyList, setProxyList] = useState([]);

  const [selectedKey, setSelectedKey] = useState(() => {
    // 初始化读取缓存，没有则默认第一个菜单
    return localStorage.getItem(MENU_STORAGE_KEY) || "startStop";
  });

  const handleMenuClick = ({ key }) => {
    // setSelectedMenu(key)
    setSelectedKey(key);
    localStorage.setItem(MENU_STORAGE_KEY, key);
  };

  useEffect(() => {
    const stored = localStorage.getItem("frp-proxy-list");
    if (stored) {
      try {
        setProxyList(JSON.parse(stored));
      } catch (e) {
        console.error("解析本地代理配置失败", e);
      }
    }
  }, []);

  useEffect(() => {
    localStorage.setItem("frp-proxy-list", JSON.stringify(proxyList));
  }, [proxyList]);

  const validateProxy = (item) => {
    return (
      item.name &&
      typeof item.name === "string" &&
      item.type &&
      typeof item.type === "string" &&
      item.local_ip &&
      typeof item.local_ip === "string" &&
      item.localPort &&
      !isNaN(Number(item.localPort))
    );
  };

  // const handleExport = () => {
  //   const blob = new Blob([JSON.stringify(proxyList, null, 2)], {
  //     type: "application/json"
  //   });
  //   const url = URL.createObjectURL(blob);
  //   const a = document.createElement("a");
  //   a.href = url;
  //   a.download = "frp-proxy-config.json";
  //   a.click();
  //   URL.revokeObjectURL(url);
  // };

  // const handleImport = (event) => {
  //   const file = event.target.files[0];
  //   if (!file) return;
  //   const reader = new FileReader();
  //   reader.onload = (e) => {
  //     try {
  //       const imported = JSON.parse(e.target.result);
  //       if (!Array.isArray(imported)) {
  //         message.error("无效的配置文件格式");
  //         return;
  //       }

  //       const validImported = imported.filter(validateProxy);
  //       if (validImported.length === 0) {
  //         message.error("导入配置无效或字段缺失");
  //         return;
  //       }

  //       const existingNames = new Set(proxyList.map((p) => p.name));
  //       const newConfigs = validImported.filter((item) => !existingNames.has(item.name));
  //       const conflictCount = validImported.length - newConfigs.length;

  //       if (newConfigs.length > 0) {
  //         setProxyList((prev) => [...prev, ...newConfigs]);
  //       }

  //       message.success(
  //         `成功导入 ${newConfigs.length} 项配置` +
  //           (conflictCount > 0 ? `，忽略重复名称 ${conflictCount} 项` : "")
  //       );
  //     } catch (err) {
  //       message.error("配置解析失败");
  //     }
  //   };
  //   reader.readAsText(file);
  // };





  const renderContent = () => {
    switch (selectedKey) {
      case "startStop":
        return <StartStop />;
      case "proxyConfig":
        return (
          <div>
            <ProxyConfig proxyList={proxyList} setProxyList={setProxyList} />
          </div>
        );
      case "versionDownload":
        return <VersionDownload />;
      case "config":
        return <ConfigPanel />;
      case "logs":
        return <Logs />;
      default:
        return null;
    }
  };

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={setCollapsed}
        theme="dark"
      >
        <div style={{ color: "#fff", padding: 16, textAlign: "center" }}>
          FRP客户端
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[selectedKey]}
          // onClick={(e) => setSelectedMenu(e.key)}
          onClick={handleMenuClick}
        >
          <Menu.Item key="startStop" icon={<PlayCircleOutlined />}>
            启动 / 停止
          </Menu.Item>
          <Menu.Item key="proxyConfig" icon={<CodeOutlined />}>
            代理配置
          </Menu.Item>
          <Menu.Item key="versionDownload" icon={<CloudDownloadOutlined />}>
            版本下载
          </Menu.Item>
          <Menu.Item key="config" icon={<SettingOutlined />}>
            配置菜单
          </Menu.Item>
          <Menu.Item key="logs" icon={<FileTextOutlined />}>
            日志菜单
          </Menu.Item>
        </Menu>
      </Sider>
      <Layout>
        <Header style={{ background: "#fff", padding: 0 }} />
        <Content style={{ margin: "16px" }}>{renderContent()}</Content>
      </Layout>
    </Layout>
  );
};

export default App;
